<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/12
 * Time: 19:33

 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com

 */


namespace app\home\controller;

use app\common\model\AmountLog;
use app\common\model\Config;
use app\common\model\DaziTopLog;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\NoticeMessage;
use app\Request;
use think\Exception;

class Dazi
{
    public function addDazi(Request $request){
        $param = $request->param();
        $data= [
            'title' => $param['title'],
            'address' => $param['address'],
            'sex' => $param['sex'],
            'pid_tab' => $param['pid_tab'],
            'son_tab' => $param['son_tab'],
            'activity_time' => strtotime($param['activity_time']),
            'expire_time' => strtotime($param['expire_time']),
            'create_time' =>  time(),
            'cover_img' => $param['cover_img'],
            'phone' => $param['phone'],
            'label' => $param['label'],
            'img' => $param['img'],
            'describe' => $param['describe'],
            'uid' => $request->userInfo['id'],
            'longitude' => $param['longitude'],
            'dimension' => $param['dimension'],
        ];
        if (isset($param['people_number'])&& !empty($param['people_number'])){
            $data['people_number'] = $param['people_number'];
        }
        if (isset($param['price'])&& !empty($param['price'])){
            $data['price'] = $param['price'];
        }
        if (isset($param['man_number'])&& !empty($param['man_number'])){
            $data['man_number'] = $param['man_number'];
        }
        if (isset($param['woman_number'])&& !empty($param['woman_number'])){
            $data['woman_number'] = $param['woman_number'];
        }
        if (isset($param['man_price'])&& !empty($param['man_price'])){
            $data['man_price'] = $param['man_price'];
        }
        if (isset($param['woman_price'])&& !empty($param['woman_price'])){
            $data['woman_price'] = $param['woman_price'];
        }
        if (strtotime($param['activity_time'])< time()){
            return error('活动不能小于当前时间');
        }
        if (strtotime($param['expire_time'])< time()){
            return error('报名时间不能小于当前时间');
        }

        if (strtotime($param['expire_time'])> strtotime($param['activity_time'])){
            return error('报名时间不能大于活动时间');
        }
        $longitude = number_format(doubleval($data['longitude']), 6);
        $latitude = number_format(doubleval($data['dimension']), 6);
        $gps = $latitude . ',' . $longitude;
        $params = array(
            'location' => $gps,
            'key'=> Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult  = json_decode(curlGet($url));
        if ($mapResult->status == 0 ){
            /* return error('百度地图数据获取有误')*/
            $data['province_name'] = $mapResult->result->address_component->province;
            $data['city_name'] = $mapResult->result->address_component->city;
            $data['area_name'] = $mapResult->result->address_component->district;
            //$user['address'] = $mapResult->result->address;
        };

        if ($request->userInfo['level_id'] > 1) {
            $dazi_number = Config::getConfigValue('level_dazi_number');
        } else {
            $dazi_number = Config::getConfigValue('dazi_number');
        }
        $daziModel = new \app\common\model\Dazi();
        if ($dazi_number  >0  ){
            $todayDaziCount = $daziModel->where('create_time'  ,strtotime(date('Y-m-d 00:00:00')))
                ->where('uid','=', $request->userInfo['id'])
                ->count();
            if ($dazi_number <= $todayDaziCount ){
                return error('今日发布数量已达上限');
            }
        }
        $isAuditing = Config::getConfigValue('dazi_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        $daziModel->insert($data);
        if ($isAuditing != 1){
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '搭子'],
                'thing2' => ['value' => $data['title']],
                'phrase3' => ['value' =>'通过'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] =$request->userInfo['id'];
            $xcxMessage[0]['title'] ='release';
            $messageModel->sendMessage(3,$xcxMessage);
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'搭子'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$data['title']],
                'thing2' => ['value' => '通过'],
            ];
            $gzhMessage[0]['uid'] =$request->userInfo['id'];
            $gzhMessage[0]['title'] ='release';
            $messageModel->sendMessage(1,$gzhMessage);
        }
        return success('添加成功');
    }
    public function daziList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where[]  =['d.status','<>',6];
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['d.status','=',$param['status']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['d.create_time','>=', strtotime($param['start_time'].'00:00:00')];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['d.create_time','<=', strtotime($param['end_time']."23:59:59")];
        }
        if (isset($param['is_oneself_uid']) && !empty($param['is_oneself_uid'])) {
            $where[] = ['d.uid','=',$param['is_oneself_uid']];
        }else{ // 不是自己创建的只看 上架中的
            $where[] = ['d.status','=',2];
            $where[] = ['d.expire_time','>',time()];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['d.uid','=',$param['uid']];
            $where[] = ['d.status','=',2];
        }
        if (isset($param['son_tab']) && !empty($param['son_tab'])){
            $where[] = ['d.son_tab','=',$param['son_tab']];
        }
        if (isset($param['dimension']) && !empty($param['dimension']) &&
            isset($param['longitude']) && !empty($param['longitude'])){
            $dimension = $param['dimension'];
            $longitude = $param['longitude'];
        }else{
            $dimension =  Config::getConfigValue('dimension') ;
            $longitude =  Config::getConfigValue('longitude') ;
        }
        if (empty($dimension)){
            $dimension = '39.54';
        }
        if (empty($longitude)){
            $longitude = '116.23';
        }

        $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$dimension}
         * PI() / 180 - d.dimension * PI() / 180) / 2), 2) + COS({$dimension} * PI() / 180)
          * COS(d.dimension * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - d.longitude * PI() / 180) / 2), 2))) 
          * 1000) AS distance";
        if (isset($param['dazi_sort_rule']) && $param['dazi_sort_rule'] == 1){
            $orderField = 'distance';
            $orderType = 'asc';
        }else{
            $orderField = 'd.create_time';
            $orderType = 'desc';
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['d.title','like','%'.$param['title'].'%'];
        }
        $userModel = new \app\common\model\User();
        $daziModel = new \app\common\model\Dazi();
        $list = $daziModel
            ->alias('d')
            ->leftJoin('user u', 'd.uid = u.id')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->leftJoin('tab_class pt', 'd.pid_tab = pt.id')
            ->where($where)
            ->field('d.*,u.nickname,u.avatar,t.name,t.type_css,t.icon,t.label_icon,
            pt.name as pt_name,pt.type_css as pt_type_css,pt.icon as pt_icon,pt.label_icon as pt_label_icon ,'.$sql)
            ->order('d.is_top','desc')
            ->order($orderField,$orderType)
            ->limit($start,$limit)->select()->toArray();
        $count = $daziModel->alias('d')
            ->leftJoin('user u', 'd.uid = u.id')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->leftJoin('tab_class pt', 'd.pid_tab = pt.id')
            ->where($where)->count();
        if ($list){
            $daziId  = array_column($list,'id');
            $daziJoinModel = new \app\common\model\DaziJoin();
            $daziJoinData = $daziJoinModel->where('dazi_id','in',$daziId)->where(['status' => 1])->select()->toArray();
            if ($daziJoinData){
                $daziJoinUid  = array_column($daziJoinData,'uid');
                $userData = $userModel->where('id','in',$daziJoinUid)
                    ->field('id,nickname,phone,avatar')
                    ->select()->toArray();
                $userDataById = array_column($userData,null,'id');
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    $daziJoinData[$daziJoinKey]['nickname']  = $userDataById[$daziJoinDatum['uid']]['nickname'];
                    $daziJoinData[$daziJoinKey]['phone']  = $userDataById[$daziJoinDatum['uid']]['phone'];
                    $daziJoinData[$daziJoinKey]['avatar']  = $userDataById[$daziJoinDatum['uid']]['avatar'];
                }
            }
            foreach ($list as $key => $value){
                $daziJoinInfo = $daziJoinModel->where('dazi_id','in',$value['id'])->order('update_time','desc')->find();
                if ($daziJoinInfo){
                    $userInfo = $userModel->where(['id' =>$daziJoinInfo['uid'] ])->field('nickname,avatar')->find();
                    $daziJoinInfo['nickname'] = $userInfo['nickname'];
                    $daziJoinInfo['avatar'] = $userInfo['avatar'];
                }
                $list[$key]['dazi_msg'] = $daziJoinInfo;
                $list[$key]['join_data'] = [];
                if ( $value['top_expire_time']  > 0 ){
                    $list[$key]['top_expire_time'] = date('Y-m-d H:i', $value['top_expire_time']);
                }
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    if ($value['id'] == $daziJoinDatum['dazi_id']){
                        $list[$key]['join_data'][]= $daziJoinDatum;
                    }
                }
                $list[$key]['distance_kilometer']  =  haversineDistance($dimension,$longitude,$value['dimension'],$value['longitude']);

            }
        }
        return success('搭子列表',['list' =>$list,'count'=>$count ]);

    }
    public function joinDazi(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziInfo = $daziModel->where(['id' =>$param['dz_id'] ])->find();
        $daziJoinInfo  = $daziJoinModel->where(['uid' => $request->userInfo['id'],'dazi_id' => $param['dz_id']])->find();
        if ($daziJoinInfo){
            if ($daziJoinInfo['status'] == 1){
                return error('已加入');
            }
        }
        if ($daziInfo['uid'] == $request->userInfo['id']){
            return error('不能加入自己的搭子');
        }
        if ($daziInfo['expire_time'] < time()){
            return error('报名时间已结束');
        }
        if ($daziInfo['status']  !=  2){
            return error('此搭子活动已关闭');
        }
        $participants_number ='participants_number';
        if ($daziInfo['sex'] == 1){
            if ($daziInfo['people_number'] == $daziInfo['participants_number']){
                return error('参与人数已满');
            }
            $price = $daziInfo['price'];
        }else{
            if ($request->userInfo['sex'] == 1){
                if ($daziInfo['man_number'] ==$daziInfo['man_participants_number'] ){
                    return error('男生参与人数已满');
                }
                $price = $daziInfo['man_price'];
                $participants_number = 'man_participants_number';
            }
            if ($request->userInfo['sex'] == 2){
                if ($daziInfo['woman_number'] == $daziInfo['woman_participants_number'] ){
                    return error('女生参与人数已满');
                }
                $price = $daziInfo['woman_price'];
                $participants_number = 'woman_participants_number';
            }
            if ($request->userInfo['sex'] == 0){
                return error('未知性别');
            }
        }
        $discountAmount = $price;
        $dazi_level_discount = 0;
        if ($request->userInfo['level_id'] > 1){
            $dazi_level_discount  = Config::getConfigValue('dazi_level_discount');
            if ($dazi_level_discount >0){
                $discountAmount = bcdiv(bcmul($price,$dazi_level_discount,2),100,2);
            }
        }
        if ($discountAmount > $request->userInfo['balance']){
            return error('余额不足请充值',[],'1001');
        }
        $data = [
            'dazi_id' => $param['dz_id'],
            'uid' => $request->userInfo['id'],
            'create_time' => time(),
            'price' => $discountAmount,
            'update_time' => time(),
            'original_price' => $price,
            'discount' => $dazi_level_discount,

        ];
        $userModel = new \app\common\model\User();
        try{
            $daziJoinModel->startTrans();
            $daziJoinModel->insert($data);
            $id  = $daziJoinModel->getLastInsID();
            if ($daziInfo['price'] > 0 ){
                  $amountModel = new AmountLog();
                  $amountData  = [
                      'uid' => $request->userInfo['id'],
                      'amount' =>$discountAmount,
                      'amount_type' => 1,
                      'amount_direction' => 2,
                      'create_time' => time(),
                      'correlation_id' => $id,
                      'operation_source' => 2,
                      'ratio' =>$dazi_level_discount,
                      'original_price' => $daziInfo['price'],
                  ];
                  $amountModel->insert($amountData);
              }
        /*    $noticeMessageModel = new  NoticeMessage();
            $noticeMessageModel->insert([
               // 'content' =>  $param['content'],
                'uid'=> $request->userInfo['id'],
                'receive_uid' => $daziInfo['uid'],
                'type' => 8,
                'dz_id' =>  $param['dz_id'],
                'create_time' => time(),
                'is_read' => 0
            ]);*/
            $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$discountAmount)->update();
            $daziModel->where(['id' => $param['dz_id']])->inc('participants_number')->inc($participants_number)->update();
            $daziJoinModel->commit();
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] =  [
                'thing6' => ['value' => $daziInfo['title']],
                'date2' => ['value' => date('Y-m-d H:i',$daziInfo['activity_time'])],
                'thing3' => ['value' => $request->userInfo['nickname']],
                'number8' => ['value' => $daziInfo['participants_number'] + 1],
                'thing11' => ['value' => '请及时和报名用户保持沟通'],
            ];
            $xcxMessage[0]['uid'] =  $daziInfo['uid'];
            $xcxMessage[0]['title'] =  'release';
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'搭子'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$daziInfo['title']],
                'thing2' => ['value' => '加入'],
            ];
            $gzhMessage[0]['uid'] =$daziInfo['uid'];
            $gzhMessage[0]['title'] ='release';
            if ($discountAmount > 0){
                $xcxMessage[1]['data'] =  [
                    'amount2' => ['value' => $discountAmount],
                    'thing8' => ['value' => '加入搭子'],
                    'thing5' => ['value' => '开始时间为'.date('Y-m-d H:i',$daziInfo['activity_time']).'请注意'],
                    'time4' =>  ['value' => date('Y-m-d H:i')],
                ];
                $xcxMessage[1]['uid'] = $request->userInfo['id'];
                $xcxMessage[1]['title'] ='consumption';
                $gzhMessage[1]['data'] = [
                    'thing2' => ['value' =>'搭子'],
                    'thing37' => ['value' => $daziInfo['title'] ],
                    'amount3' => ['value' =>$discountAmount],
                    'time3' => ['value' => date('Y-m-d H:i')],
                ];
                $gzhMessage[1]['uid'] =$request->userInfo['id'];
                $gzhMessage[1]['title'] ='consumption';
            }
            $messageModel-> sendAliMessage($daziInfo['uid'], 'release', ['name' =>'搭子'. $daziInfo['name'],'desc'=>'有用户加入']);

            $messageModel->sendMessage(1,$gzhMessage);
            $messageModel->sendMessage(3,$xcxMessage);
        }catch ( Exception $exception){
            $daziJoinModel->rollback();
            return error($exception->getMessage().$exception->getLine());
        }
        return success('参入成功');
    }
    public function updateDaziStatus(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $daziJoinModel = new \app\common\model\DaziJoin();
        if ($param['status'] == 3 || $param['status'] == 7 ||$param['status'] == 6){
            $daziJoinInfo =  $daziJoinModel->where(['dazi_id' => $param['id'],'status' => 1 ])->select()->toArray();
            if ($daziJoinInfo){
                return  error('存在参与的用户，不能下架');
            }
        }
        $data['status']  =  $param['status'];
        $daziModel->where(['id' => $param['id']])->update($data);

        return  success('操作成功');
    }
    public function updateDazi(Request $request){
        $param = $request->param();

        $data= [
            'title' => $param['title'],
            'address' => $param['address'],
            'sex' => $param['sex'],
            'pid_tab' => $param['pid_tab'],
            'son_tab' => $param['son_tab'],
            'activity_time' => strtotime($param['activity_time']),
            'expire_time' => strtotime($param['expire_time']),
            'create_time' =>  time(),
            'cover_img' => $param['cover_img'],
            'phone' => $param['phone'],
            'label' => $param['label'],
            'img' => $param['img'],
            'describe' => $param['describe'],
            'uid' => $request->userInfo['id'],
            'longitude' => $param['longitude'],
            'dimension' => $param['dimension'],
        ];
        if (isset($param['people_number'])&& !empty($param['people_number'])){
            $data['people_number'] = $param['people_number'];
        }
        if (isset($param['price'])&& !empty($param['price'])){
            $data['price'] = $param['price'];
        }
        if (isset($param['man_number'])&& !empty($param['man_number'])){
            $data['man_number'] = $param['man_number'];
        }
        if (isset($param['woman_number'])&& !empty($param['woman_number'])){
            $data['woman_number'] = $param['woman_number'];
        }
        if (isset($param['man_price'])&& !empty($param['man_price'])){
            $data['man_price'] = $param['man_price'];
        }
        if (isset($param['woman_price'])&& !empty($param['woman_price'])){
            $data['woman_price'] = $param['woman_price'];
        }
        if (strtotime($param['activity_time'])< time()){
            return error('活动不能小于当前时间');
        }
        if (strtotime($param['expire_time'])< time()){
            return error('报名时间不能小于当前时间');
        }

        if (strtotime($param['expire_time'])> strtotime($param['activity_time'])){
            return error('报名时间不能大于活动时间');
        }
        $longitude = number_format(doubleval($data['longitude']), 6);
        $latitude = number_format(doubleval($data['dimension']), 6);
        $gps = $latitude . ',' . $longitude;

        $params = array(
            'location' => $gps,
            'key'=> Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult  = json_decode(curlGet($url));
        if ($mapResult->status == 0 ){
            /* return error('百度地图数据获取有误')*/
            $data['province_name'] = isset ($mapResult->result->address_component->province)?$mapResult->result->address_component->province :0 ;
            $data['city_name'] = $mapResult->result->address_component->city;
            $data['area_name'] = $mapResult->result->address_component->district;
            //$user['address'] = $mapResult->result->address;
        };
        $isAuditing = Config::getConfigValue('dazi_status');
        if ($isAuditing == 1){
            $data['status']  = '1';
        }else{
            $data['status']  = '2';
        }
        $daziModel = new \app\common\model\Dazi();
        $daziInfo = $daziModel->where(['id' => $param['id']])->find();
        if ($daziInfo['participants_number']){
            return error('已有用户参与');
        }
        $daziModel->where(['id' => $param['id']])->update($data);
        return success('修改成功');
    }
    public function daziInfo(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $usreModel = new \app\common\model\User();
        $daziInfo =  $daziModel->where(['id' => $param['id']])->find();
        $userInfo =  $usreModel->where(['id' => $daziInfo['uid']])->find();
        $daziInfo['nickname']  =  $userInfo['nickname'];
        $daziInfo['avatar']  =  $userInfo['avatar'];
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziJoinUser = $daziJoinModel->where(['dazi_id' =>$param['id']])->where(['status' =>1])->select()->toArray();

        $tabModel = new \app\common\model\TabClass();
        $tabInfo = $tabModel = $tabModel->where(['id' =>$daziInfo['pid_tab'] ])->find();
        $daziInfo['pt_type_css'] = $tabInfo['type_css'];
        $daziInfo['pt_label_icon'] = $tabInfo['label_icon'];
        if (empty($daziJoinUser)){
            $daziInfo['dazi_join_user'] = [];
        }else{
            $joinUid =array_column($daziJoinUser,'uid');
            $userModel = new \app\common\model\User();
            $userList = $userModel->where('id','in',$joinUid)
                ->field('id,nickname,avatar,sex,age')
                ->select()->toArray();
            $userListById = array_column($userList,null,'id');
            foreach ($daziJoinUser as $key => $value){
                $daziJoinUser[$key]['nickname'] = $userListById[$value['uid']]['nickname'];
                $daziJoinUser[$key]['avatar'] = $userListById[$value['uid']]['avatar'];
                $daziJoinUser[$key]['sex'] = $userListById[$value['uid']]['sex'];
                $daziJoinUser[$key]['age'] = $userListById[$value['uid']]['age'];
            }
            $daziInfo['dazi_join_user'] = $daziJoinUser;
        }
        return success('搭子详情',$daziInfo);

    }
    public function joinDaziList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['dj.uid','=',$request->userInfo['id']];
        if (isset($param['status']) &&  !empty($param['status'])) {
            $where[] = ['d.status','=',$param['status']];
        }
        if (isset($param['dj_status']) &&  !empty($param['dj_status'])) {
            $where[] = ['dj.status','=',$param['dj_status']];
        }
        if (isset($param['title']) && !empty($param['title'])){
            $where[] = ['d.title','like','%'.$param['title'].'%'];
        }
        $daziJoinModel = new \app\common\model\DaziJoin();
        $list = $daziJoinModel
            ->alias('dj')
            ->leftJoin('dazi d', 'd.id = dj.dazi_id')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->leftJoin('tab_class pt', 'd.pid_tab = pt.id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->where($where)
            ->order('dj.create_time','desc')
            ->field('d.*,u.nickname,u.avatar,dj.status as dj_status,t.name,t.type_css,t.icon,t.label_icon,
              pt.name as pt_name,pt.type_css as pt_type_css,pt.icon as pt_icon,pt.label_icon as pt_label_icon')
            ->limit($start,$limit)->select()->toArray();
        if ($list){
            $daziId  = array_column($list,'id');
            $daziJoinModel = new \app\common\model\DaziJoin();
            $daziJoinData = $daziJoinModel->where('dazi_id','in',$daziId)->where(['status' => 1])->select()->toArray();
            $userModel = new \app\common\model\User();
            if ($daziJoinData){
                $daziJoinUid  = array_column($daziJoinData,'uid');
                $userData = $userModel->where('id','in',$daziJoinUid)
                    ->field('id,nickname,phone,avatar')
                    ->select()->toArray();
                $userDataById = array_column($userData,null,'id');
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    $daziJoinData[$daziJoinKey]['nickname']  = $userDataById[$daziJoinDatum['uid']]['nickname'];
                    $daziJoinData[$daziJoinKey]['phone']  = $userDataById[$daziJoinDatum['uid']]['phone'];
                    $daziJoinData[$daziJoinKey]['avatar']  = $userDataById[$daziJoinDatum['uid']]['avatar'];
                }
            }
            foreach ($list as $key => $value){
                $daziJoinInfo = $daziJoinModel->where('dazi_id','in',$value['id'])->order('update_time','desc')->find();
                if ($daziJoinInfo){
                    $userInfo = $userModel->where(['id' =>$daziJoinInfo['uid'] ])->field('nickname,avatar')->find();
                    $daziJoinInfo['nickname'] = $userInfo['nickname'];
                    $daziJoinInfo['avatar'] = $userInfo['avatar'];
                }
                $list[$key]['dazi_msg'] = $daziJoinInfo;
                $list[$key]['join_data'] = [];
                foreach ($daziJoinData as $daziJoinKey => $daziJoinDatum){
                    if ($value['id'] == $daziJoinDatum['dazi_id']){
                        $list[$key]['join_data'][]= $daziJoinDatum;
                    }
                }
            }
        }
        $count = $daziJoinModel
            ->alias('dj')
            ->leftJoin('dazi d', 'd.id = dj.dazi_id')
            ->leftJoin('tab_class t', 'd.son_tab = t.id')
            ->leftJoin('user u', 'd.uid = u.id')
            ->where($where)
            ->field('d.*,u.nickname,u.avatar ,dj.status as dj_status')
            ->count();
        return success('我参与的搭子列表',['list' =>$list,'count'=>$count ]);
    }
    public  function  endTime(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $daziModel->where(['id' => $param['id']])->update(['expire_time' => time(),'is_start'=> 1]);
        return  success('操作成功');
    }
    public  function  kickUser(Request $request){
        $param = $request->param();
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziJoinInfo  = $daziJoinModel->where(['id' => $param['id']])->find();
        $daziModel = new \app\common\model\Dazi();
        if ($daziJoinInfo['status'] != 1 ){
            return error('此用户已踢出');
        }
        $daziJoinModel->where(['id' => $param['id']])->update(['status' => 2,'update_time' => time()]);
        if ($daziJoinInfo['price']){
            $userModel = new \app\common\model\User();
            $userModel->where(['id' =>$daziJoinInfo['uid'] ])->inc('balance',$daziJoinInfo['price'])->update();
            $userInfo = $userModel->where(['id' =>$daziJoinInfo['uid'] ])->find();
            $daziInfo =    $daziModel->where(['id' =>$daziJoinInfo['dazi_id'] ])->find();
            if ($userInfo['sex'] == 1){
                $participants_number = 'man_participants_number';
            }else{
                $participants_number = 'woman_participants_number';
            }
            $daziModel->where(['id' =>$daziJoinInfo['dazi_id'] ])->dec('participants_number')->dec($participants_number)->update();
            $amountModel = new AmountLog();
            $amountData  = [
                'uid' => $daziJoinInfo['uid'],
                'amount' => $daziJoinInfo['price'],
                'amount_type' => 1,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id' => $param['id'],
                'operation_source' => 3
            ];
            $amountModel->insert($amountData);
        /*    $noticeMessageModel = new  NoticeMessage();
            $noticeMessageModel->insert([
                // 'content' =>  $param['content'],
                'uid'=> $request->userInfo['id'],
                'receive_uid' => $daziJoinInfo['uid'],
                'type' => 9,
                'dz_id' =>  $daziJoinInfo['dz_id'],
                'create_time' => time(),
                'is_read' => 0
            ]);*/
            $messageModel = new MessageTemplate();
            $xcxMessage[0]['data'] = [
                'thing1' => ['value' => '搭子'],
                'thing2' => ['value' => $daziInfo['title']],
                'phrase3' => ['value' =>'已被搭子主移除'],
                'time5' => ['value' => date('Y-m-d H:i:s')],
            ];
            $xcxMessage[0]['uid'] =$daziJoinInfo['uid'];
            $xcxMessage[0]['title'] ='release';
            $gzhMessage[0]['data'] = [
                'thing10' => ['value' =>'搭子'],
                'thing28' => ['value' => $request->userInfo['nickname'] ],
                'thing9' => ['value' =>$daziInfo['title']],
                'thing2' => ['value' => '移除'],
            ];
            $gzhMessage[0]['uid'] =$request->userInfo['id'];
            $gzhMessage[0]['title'] ='release';
            $messageModel->sendMessage(3,$xcxMessage);
            $messageModel->sendMessage(1,$gzhMessage);
            $messageModel-> sendAliMessage($daziJoinInfo['uid'], 'release', ['name' =>'搭子'. $daziInfo['name'],'desc'=>'被踢出']);

        }
        return  success('操作成功');
    }
    public  function  signOut(Request $request){
        $param = $request->param();
        $daziModel = new \app\common\model\Dazi();
        $daziInfo  = $daziModel->where(['id' => $param['id']])->find();
        $daziJoinModel = new \app\common\model\DaziJoin();
        $daziJoinInfo  = $daziJoinModel->where(['dazi_id' => $param['id'],'uid' => $request->userInfo['id'],'status' => 1])->find();
        if (empty($daziJoinInfo)){
            return error('已退出');
        }
        $daziJoinModel->where(['id' => $daziJoinInfo['id']])->update(['status' => 3,'update_time' => time()]);
        if ($daziJoinInfo['price']){
            $dz_signout_rate  = Config::getConfigValue('dz_signout_rate');
            $handling_deduction = 0;
            if ($dz_signout_rate>0){
                $handling_deduction =  bcdiv(bcmul($dz_signout_rate,$daziJoinInfo['price'],2),100,2);
                $surplusAmount  = bcsub($daziJoinInfo['price'],$handling_deduction,2);
            }else{
                $surplusAmount  = $daziJoinInfo['price'];
            }
            $userModel = new \app\common\model\User();
            $userModel->where(['id' =>$daziJoinInfo['uid'] ])->inc('balance',$surplusAmount)->update();
            if ($request->userInfo['sex'] == 1){
                $participants_number = 'man_participants_number';
            }else{
                $participants_number = 'woman_participants_number';
            }
            $daziModel->where(['id' =>$daziJoinInfo['dazi_id'] ])->dec('participants_number')
                ->dec($participants_number)->update();
            $amountModel = new AmountLog();
            $amountData  = [
                'uid' => $request->userInfo['id'],
                'amount' => $surplusAmount,
                'amount_type' => 1,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id' => $daziJoinInfo['id'],
                'operation_source' => 3,
                'ratio' => $dz_signout_rate,
                'handling_fees' => 0
            ];
            $amountModel->insert($amountData);
            if ($handling_deduction){
                $amountModel = new AmountLog();
                $amountData  = [
                    'uid' =>$daziInfo['uid'],
                    'amount' => $handling_deduction,
                    'amount_type' => 2,
                    'amount_direction' => 1,
                    'create_time' => time(),
                    'correlation_id' => $daziJoinInfo['id'],
                    'operation_source' => 11,
                    'ratio' => $dz_signout_rate,
                    'handling_fees' => 0
                ];
                $amountModel->insert($amountData);
                $userModel->where(['id' =>$daziInfo['uid'] ])
                    ->inc('dazi_income',$surplusAmount)
                    ->inc('surplus_income',$surplusAmount)
                    ->inc('total_income',$surplusAmount)
                    ->update();
            }
           /* $noticeMessageModel = new  NoticeMessage();
            $noticeMessageModel->insert([
                // 'content' =>  $param['content'],
                'uid'=> $request->userInfo['id'],
                'receive_uid' => $daziInfo['uid'],
                'type' => 10,
                'dz_id' =>  $param['id'],
                'create_time' => time(),
                'is_read' => 0
            ]);*/
        }
        $xcxMessage[0]['data'] = [
            'thing1' => ['value' => '搭子'],
            'thing2' => ['value' => $daziInfo['title']],
            'phrase3' => ['value' =>'用户退出'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] =$daziInfo['uid'];
        $xcxMessage[0]['title'] ='release';
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' =>'搭子'],
            'thing28' => ['value' => $request->userInfo['nickname'] ],
            'thing9' => ['value' =>$daziInfo['title']],
            'thing2' => ['value' => '退出'],
        ];
        $gzhMessage[0]['uid'] =$daziInfo['uid'];
        $gzhMessage[0]['title'] ='release';
        $messageModel = new MessageTemplate();
        $messageModel->sendMessage(3,$xcxMessage);
        $messageModel->sendMessage(1,$gzhMessage);
        $messageModel-> sendAliMessage($daziInfo['uid'], 'release', ['name' =>'搭子'. $daziInfo['name'],'desc'=>'有用户退出']);

        return  success('操作成功');
    }
    public function top(Request $request){
        $param = $request->param();
        if ($param['day']<= 0){
            return error('请设置正确的天数');
        }
        $daziTopNumber =  Config::getConfigValue('dazi_top_number');
        $daziModel =  new \app\common\model\Dazi();
        $count = $daziModel->where(['is_top' => 1,'status' => 2])->count();
        if ($count >= $daziTopNumber ){
            return error('置顶数量已经最大');
        }
        $daziInfo = $daziModel->where(['id' => $param['id']])->find();
        if ($daziInfo['uid'] != $request->userInfo['id']){
            return error('请操作自己的搭子');
        }

        if ($daziInfo['top_expire_time'] > time()){
            $effective_time_start =  $daziInfo['top_expire_time'];
        }else{
            $effective_time_start = time();
        }
        $day = ceil(($daziInfo['expire_time'] - $effective_time_start)/86400);
        if ($param['day'] > $day ){
            return error('此搭子置顶时间只能设置'.$day.'天');
        }
        $dazi_top_price =  Config::getConfigValue('dazi_top_price');
        $dazi_top_level_ratio = 0;
        $original_price = bcmul($dazi_top_price,$param['day'],2);
        $total_price = $original_price;
        if ($request->userInfo['level_id'] > 1){
            $dazi_top_level_ratio  = Config::getConfigValue('dazi_top_level_ratio');
            if ($dazi_top_level_ratio > 0){
                $total_price = bcdiv(bcmul($total_price,$dazi_top_level_ratio,2),100,2);
            }
        }
        if ($request->userInfo['balance'] < $total_price) {
            return error('余额不足');
        }
        $data = [
            'dazi_id' =>$param['id'],
            'uid' => $request->userInfo['id'],
            'unit_price' => $dazi_top_price,
            'total_price' =>  $total_price,
            'day' => $param['day'],
            'ratio' => $dazi_top_level_ratio,
            'effective_time' => $effective_time_start +  bcmul($param['day'],86400,2),
            'original_price' => $original_price,
        ];
        $daziTopLogModel = new DaziTopLog();
        $daziTopLogModel->insert($data);
        $daziTopLogId = $daziTopLogModel->getLastInsID();
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $request->userInfo['id']])->dec('balance',$data['total_price'])->update();
        $recharge_ratio = Config::getConfigValue('recharge_ratio');
        $handling_fees_amount =  bcdiv($data['total_price'],$recharge_ratio,2);
        $daziModel->where(['id' => $param['id']])->update(['is_top' => 1,'top_expire_time' => $data['effective_time']]);
        $amountData = [
            'uid' =>   $request->userInfo['id'],
            'amount' => $data['total_price'],
            'amount_type' => 1,
            'operation_source' => 20,
            'amount_direction' => 2,
            'create_time' => time(),
            'correlation_id'  => $daziTopLogId,
            'ratio' => 1,
            'original_price' =>$original_price,
            'handling_fees' =>$data['total_price'],
            'handling_fees_amount' =>$handling_fees_amount
        ];
        $amountModel = new   AmountLog();
        $amountModel->insert($amountData);
        return success('操作成功');
    }



}